package com.btr.ivle.backgroud;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import android.content.Context;
import android.os.AsyncTask;

import com.btr.ivle.R;
import com.btr.ivle.data.IVLEToken;

public class PostForumTask extends AsyncTask<String, Void, String> {
	
	private Context context;
	
	public PostForumTask(Context context){
		this.context = context;
	}
	
	protected String doInBackground(String... texts) {
    	HttpClient httpclient = new DefaultHttpClient();
    	HttpPost httppost;
    	Boolean newPost = Boolean.valueOf(texts[3]);
    	if(newPost){
    		httppost = new HttpPost("https://ivle.nus.edu.sg/api/Lapi.svc/Forum_PostNewThread_JSON");
    	}else{
    		httppost = new HttpPost("https://ivle.nus.edu.sg/api/Lapi.svc/Forum_ReplyThread_JSON");
    	}

        String result= "";
        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("APIKey", context.getString(R.string.IVLE_API_KEY) + ""));
            nameValuePairs.add(new BasicNameValuePair("AuthToken", IVLEToken.getToken()));
            nameValuePairs.add(new BasicNameValuePair("Title",texts[1]));
            nameValuePairs.add(new BasicNameValuePair("Reply",texts[2]));
            
            if(newPost){
            	nameValuePairs.add(new BasicNameValuePair("HeadingID",texts[0]));
            }else{
            	nameValuePairs.add(new BasicNameValuePair("ThreadID",texts[0]));
            }
            // Execute HTTP Post Request
            httppost.addHeader("charset", HTTP.UTF_8);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
            HttpResponse response = httpclient.execute(httppost);
            long length = response.getEntity().getContentLength();
            InputStream contentStream = response.getEntity().getContent();
            byte[] b = new byte[(int) length];
            contentStream.read(b, 0, (int)length);
            result = new String(b,0,(int)length);
            
        } catch (ClientProtocolException e) {
        } catch (IOException e) {
        }
		return result;
        
    }

    @SuppressWarnings("unchecked")
	protected void onPostExecute(String result) {
    	AsyncTaskCompleteListener<String> l = (AsyncTaskCompleteListener<String>) context;
    	l.onAsyncTaskComplete("");
    }
}